<template>
  <div class="table-page">
    <!-- 文章列表 -->
    <div class="title-box">关联关键词</div>
    <a-form label-align="right" auto-label-width :model="form" class="form">
      <a-row :gutter="16" wrap>
        <a-col :xs="12" :md="12" :lg="8" :xl="6" :xxl="6">
          <a-form-item field="mobile" label="关键词">
            <a-input v-model="form.keyword" placeholder="请输入关键词" />
          </a-form-item>
        </a-col>
        <a-col :xs="12" :md="12" :lg="8" :xl="6" :xxl="6">
          <a-form-item field="category_id" label="类别">
            <a-select
              allow-search
              v-model="form.category_id"
              placeholder="请选择类别"
              allow-clear
              :loading="loadingCategory"
              @popup-visible-change="handleLoadingCategory"
            >
              <a-option v-for="item in categoryData" :value="item.value">{{ item.label }}</a-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :xs="12" :md="12" :lg="8" :xl="6" :xxl="6">
          <a-space>
            <a-button type="primary" @click="getTableData">
              <template #icon>
                <icon-search />
              </template>
              <template #default>查询</template>
            </a-button>
            <a-button @click="handleReset">
              <template #default>重置</template>
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-form>
    <div class="operation-line">
      <a-space align="center">
        <weekList v-model="currentDate"></weekList>
        <a-link
          v-if="currentDate && format(currentDate, 'yyyy-MM-dd') != format(new Date(), 'yyyy-MM-dd')"
          @click="() => (currentDate = new Date())"
          >回到今日</a-link
        >
        <a-date-picker style="width: 268px" v-model="currentDate">
          <a-button>
            <template #icon>
              <icon-calendar :size="18" />
            </template>
          </a-button>
        </a-date-picker>
        <a-checkbox v-model="isAllDate" @change="handleChangeAll">全部</a-checkbox>
      </a-space>
    </div>
    <section class="table-box">
      <a-table
        row-key="id"
        size="small"
        page-position="bl"
        :bordered="{ cell: true }"
        :loading="loading"
        :data="tableData"
        :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
        :pagination="{ showPageSize: true, showTotal: true, total: total, current: current, pageSize: pageSize }"
        @page-change="changeCurrent"
        @page-size-change="changePageSize"
        :row-selection="rowSelection"
        @selection-change="handleSelectionChange"
        style="height: calc(100% - 50px)"
      >
        <template #columns>
          <a-table-column title="ID" :width="68" data-index="id"> </a-table-column>
          <a-table-column title="类别" :width="120" data-index="category">
            <template #cell="{ record }">
              {{ record.category?.name }}
            </template>
          </a-table-column>
          <a-table-column title="关键词" data-index="name"></a-table-column>
          <a-table-column title="标题" data-index="title"></a-table-column>
        </template>
        <template v-if="selectKeysTable.length" #footer>
          <span>已选择 {{ selectKeysTable.length }} 条数据</span>
        </template>
      </a-table>
      <div class="choose-modal" style="display: flex; justify-content: flex-end">
        <a-form-item style="width: min-content" field="status" label="选择模板">
          <a-select
            allow-search
            style="width: 200px"
            @dropdown-reach-bottom="getTemplateData()"
            :loading="loadingTemp"
            @search="handleSearch"
            v-model="chooseModal"
            placeholder="请选择类型"
            allow-clear
          >
            <a-option v-for="item in templateOption" :value="item.id">{{ item.name }}({{ item.type_text }})</a-option>
          </a-select>
          <icon-bar-chart style="cursor: pointer; margin-left: 8px" size="18" @click="() => chartModalRef.show()" />
          <a-popconfirm content="确定生成?" @ok="handleRelation">
            <a-button :disabled="!selectKeysTable.length || !chooseModal" style="margin-left: 12px" type="primary">
              <template #default>确认生成</template>
            </a-button>
          </a-popconfirm>
        </a-form-item>
      </div>
    </section>
    <chartModal :tabList="statusOption" ref="chartModalRef"></chartModal>
  </div>
</template>

<script setup lang="ts" name="MainTable">
import { reactive, ref } from 'vue'
import { usePagination } from '@/hooks'
import { getKeywordList, getStatusOptions, getKeyWordTypeList, getTemplateList, relationKeywordsAudit } from '@/apis'
import { useRouter } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import { format } from 'date-fns'
import weekList from '@/components/thesaurus-management/weekList.vue'
import chartModal from '@/views/template-management/chartModal.vue'

const chartModalRef = ref(null)
const chooseModal = ref('')
// 表格选择
const rowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: true,
  onlyCurrent: false
})
const currentDate = ref(new Date())
const router = useRouter()
const form = reactive({
  keyword: '',
  category_id: ''
})
const loading = ref(false)
const tableData = ref([])

const { current, pageSize, total, changeCurrent, changePageSize, setTotal } = usePagination(() => getTableData())

const templatepager = reactive({
  page: 1,
  pageSize: 100,
  total: 0
})
const templateOption = ref([])
const loadingTemp = ref(false)
// 获取模板下拉
const getTemplateData = async (query?: string) => {
  loadingTemp.value = true
  const res = await getTemplateList({
    status: 1,
    keyword: query || '',
    page: templatepager.page,
    pagesize: templatepager.pageSize
  }).then((res) => {
    if (res.code == 1) {
      if (res.data.data?.length > 0) {
        templateOption.value = templateOption.value.concat(res.data.data || []).filter((dd) => dd.status == 1)
        templatepager.page++
      }
    } else {
    }
    loadingTemp.value = false
  })
}
getTemplateData()

// 搜索
const handleSearch = (val) => {
  templatepager.page = 1
  templateOption.value = []
  getTemplateData(val)
}

const getTableData = async () => {
  loading.value = true
  let params = {
    page: current.value,
    pagesize: pageSize.value,
    ...form,
    status: '0'
  }
  if (currentDate.value) {
    params.date = format(currentDate.value, 'yyyy-MM-dd')
  }
  const resData = await getKeywordList(params)

  if (resData.code == 1) {
    tableData.value = resData.data.data
    setTotal(resData.data.total)
    loading.value = false
  } else {
    loading.value = false
  }
}
const handleReset = () => {
  form.keyword = ''
  form.status = ''
  form.category_id = ''
  getTableData()
}
getTableData()
const selectKeysTable = ref([])
const handleSelectionChange = (arr) => {
  selectKeysTable.value = arr
}
// 获取状态下拉
const statusOption = ref([])
const getStatusOption = async (visible) => {
  if (!visible) return
  let res = await getStatusOptions()
  if (res.code == 1) {
    statusOption.value = res.data.type || []
  }
}
getStatusOption(true)

// 获取下拉列表
const categoryPage = {
  page: 1,
  pagesize: 1000
}
const categoryData = ref([])
const loadingCategory = ref(false)
const handleLoadingCategory = (visible: boolean) => {
  if (visible) {
    loadingCategory.value = true
    getKeyWordTypeList(categoryPage).then((res) => {
      if (res.code == 1) {
        categoryData.value = (res.data.data || []).map((dd) => {
          return {
            label: dd.name,
            value: dd.id
          }
        })
      } else {
      }
      loadingCategory.value = false
    })
  }
}
const handleRelation = async () => {
  let tempKeyArr = tableData.value.filter((dd) => selectKeysTable.value.includes(dd.id)).map((dd) => dd.id)
  let keywords = tempKeyArr.join('#')
  let template_id = chooseModal.value
  let res = await relationKeywordsAudit({
    template_id,
    type: 2,
    keywords
  })
  if (res.code == 1) {
    Message.success(res.msg || '关联成功')
    getTableData()
    setTimeout(() => {
      router.push({ path: '/audit-management/article-list' })
    }, 500)
  } else {
    Message.error(res.msg || '关联失败')
  }
}
watch(
  () => currentDate.value,
  () => {
    getTableData()
    if (currentDate.value) {
      isAllDate.value = false
    }
  }
)
const isAllDate = ref(false)
const handleChangeAll = (checked: boolean) => {
  if (checked) {
    currentDate.value = ''
  } else {
    currentDate.value = new Date()
  }
}
</script>

<style lang="scss" scoped>
:deep(.arco-grid) {
  flex-wrap: wrap;
}
:deep(.arco-grid-item) {
  min-width: 250px;
}
:deep(.arco-alert-success) {
  padding: 14px 16px;
  border-color: rgb(var(--success-6));
  background-color: rgba(var(--success-6), 0.08);
  .arco-alert-content {
    color: rgb(var(--success-6));
    font-size: 12px;
  }
}
.table-page {
  height: 100%;
  overflow: hidden;
  margin: $margin;
  background: var(--color-bg-1);
  padding: $padding;
  padding-bottom: 0;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  .title-box {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 8px;
  }
  .form {
    margin-top: 12px;
    :deep(.arco-form-item) {
      margin-bottom: 10px;
    }
  }
  .operation-line {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 8px 0;
  }
  .table-box {
    flex: 1;
    overflow: hidden;
    margin-top: 12px;
  }
}
</style>
